﻿using MediatR;
using Microsoft.AspNetCore.Mvc;
using TaskProject.Application.Command.BOM;
using TaskProject.Domain.BOM;
using TaskProject.ErrorCode;
using TaskProject.Extension;
using TaskProject.InfrasIntructure.Interface;

namespace TaskProject.Application.Handler.BOM
{
    public class GetOneBOMHandler : IRequestHandler<GetOneBOMCommand, APIResult<BOMDTO>>
    {
        IBaseRepository<BOMModel> bomRepo;
        IBaseRepository<ProductModel> proRepo;
        IBaseRepository<MaterialModel> materRepo;

        public GetOneBOMHandler(IBaseRepository<BOMModel> bomRepo, IBaseRepository<ProductModel> proRepo, IBaseRepository<MaterialModel> materRepo)
        {
            this.bomRepo = bomRepo;
            this.proRepo = proRepo;
            this.materRepo = materRepo;
        }

        public Task<APIResult<BOMDTO>> Handle(GetOneBOMCommand request, CancellationToken cancellationToken)
        {
            APIResult<BOMDTO> res=new APIResult<BOMDTO>();
            var boms=bomRepo.GetAll().Where(c=>c.BOMId==request.BOMId && !c.IsDel);
            var pro = proRepo.GetAll().Where(c => !c.IsDel);
            var mater = materRepo.GetAll().Where(c => !c.IsDel);
            var list = from a in boms
                       join b in pro on a.ProductId equals b.ProductId
                       join c in mater on a.MaterialId equals c.MaterialId
                       select new BOMDTO
                       {
                           BOMId = a.BOMId,
                           BOMtheme = a.BOMtheme,
                           BOMDesc = a.BOMDesc,
                           BOMState = a.BOMState,
                           BOMVersion = a.BOMVersion,
                           ProductId = b.ProductId,
                           ProductName = b.ProductName,
                           ProductType = b.ProductType,
                           MaterialId = c.MaterialId,
                           MaterialName = c.MaterialName,
                           Specification = c.Specification,
                           UnitName = c.UnitName,
                           Brand = c.Brand,
                           DayNum = a.DayNum,
                           PartNum = a.PartNum,
                           LossRate = a.LossRate,
                           CreateDesc = a.CreateDesc,
                           CreteDate = a.CreteDate,
                           CreteName = a.CreteName
                       };
            var lists = list.FirstOrDefault();
            res.Msg = "查询BOM信息成功";
            res.Code = APIEnum.Success;
            res.Data = lists;
            return Task.FromResult(res);

        }
    }
}
